<template>
  <layout-slot :reArticle="reArticle" v-cloak bodyImage="" class="article-main" class-name="article-content">

    <!-- 非移动端展示 -->
    <div class="post-header-thumb  bg-orange"
         :style="{backgroundImage:`url(${articleDetail.src})`}">
      <div class="post-header-thumb-op"
           :style="{backgroundImage:`url(${articleDetail.src})`}"></div>
      <div class="post-header-thumb-cover">
        <div class="post-header-thumb-container">
          <div class="post-header-thumb-title">
            {{ articleDetail.title }}
          </div>
          <div class="post-header-thumb-meta">
            <time datetime="2021-04-04T16:09:00+08:00" itemprop="datePublished">
              <i class="fa fa-clock-o" aria-hidden="true"> </i>
              {{ articleDetail.time | dateFormat('{y}-{m}-{d}') }}
            </time>
            &nbsp;
            <span>
              <i class="fa fa-tags" aria-hidden="true"></i>
              <a v-for="(tmp,index) in articleDetail.category.url.split(',')" :href="'/category/' + tmp"
                 style="padding: 0">
                {{ `${articleDetail.category.title.split(',')[index]}`  }}{{ (index !== articleDetail.category.url.split(',').length - 1) ? ',' : '' }}
              </a>
            </span>
            &nbsp;
            <i class="fa fa-comments-o" aria-hidden="true"></i>
            <a v-if="articleDetail.comments" href="#comments">
              {{ articleDetail.comments.number }} {{ $t('comments') }}
            </a>
            &nbsp;
            <i class="fa fa-eye" aria-hidden="true"></i>{{ articleDetail.views }} {{ $t('views') }}
          </div>
          <div class="post-tags">
            <a :key="index" v-for="(item,index) of articleDetail.tags" :href="item.url">
              {{ item.name }}
            </a>
          </div>
        </div>
      </div>
    </div>
    <!-- 文章主体 -->
    <article ref="article_body" class="main-content post-page" itemscope="" itemtype="http://schema.org/Article">

      <!-- mobile -->
      <div class="post-header">
        <h1 class="post-title" itemprop="name headline">{{ articleDetail.title }}</h1>
        <div class="post-data">
          <time datetime="2021-04-04T16:09:00+08:00" itemprop="datePublished">
            <i class="fa fa-clock-o" aria-hidden="true"> </i> {{articleDetail.time | dateFormat('{y}-{m}-{d}') }}
          </time>
          &nbsp;
          <span>
              <i class="fa fa-tags" aria-hidden="true"></i>
              <a v-for="(tmp,index) in articleDetail.category.url.split(',')" :href="'/category/' + tmp"
                 style="padding: 0">
                {{ `${articleDetail.category.title.split(',')[index]}`  }}{{ (index !== articleDetail.category.url.split(',').length - 1) ? ',' : '' }}
              </a>
          </span>
          &nbsp;
          <i class="fa fa-comments-o" aria-hidden="true"></i>
          <a v-if="articleDetail.comments" href="#comments">
            {{ articleDetail.comments.number }} {{ $t('comments') }}
          </a>
          &nbsp;
          <i class="fa fa-eye" aria-hidden="true"></i>
          {{ articleDetail.views }} {{ $t('views') }}
        </div>
      </div>

      <div id="post-content" class="post-content" itemprop="articleBody">
        <p class="post-tags">
          <a :key="index" v-for="(item,index) of articleDetail.tags" :href="item.url">{{ item.name }}
          </a>
        </p>
        <div class="protected" v-if="articleDetail.auth === 0">
<!--          <p class="word">访问验证码漪悼遛，进不去请点击<b> 关于 </b>联系站长获取。</p>-->
          <p><input v-model="password" type="password" class="text" name="protectPassword" @keyup.enter="articleByPass">
            <span v-html="'&nbsp;&nbsp;&nbsp;'"></span>
            <input type="button" class="submit" value="提交" @click="articleByPass"></p>
        </div>
        <!-- body start -->
        <div ref="article_main" v-html="articleDetail.body"></div>
        <!-- body end -->
      </div>
      <p class="post-info">
      </p>
      <div style="text-align: center;">
      <span
        v-if="articleDetail.footerStatement"
        v-html=
          "$t('statement')
          .replace('XXX',articleDetail.footerStatement.url)
          .replace('YYY',$t('article-detail.author'))
          .replace('ZZZ',articleDetail.footerStatement.updateTime)"
      ></span>
        <!--        如果你觉得我的文章不错，不妨鼓励我继续写作。-->
        <span>{{$t('article-detail.end')}}</span>
      </div>
      <div id="rewardButton"
           style="padding: 10px 0; margin: 20px auto; width: 100%; font-size:16px; text-align: center;">
        <div id="reward-qr-code" style="padding: 50px;background-color: #393D49; color: #fff;display: none;"><img
          style="width: 100%;" src="https://rawchen.com/qrcode.jpg"></div>
        <button type="button" @click.stop="showSupportModal  = true">打赏</button>
      </div>
      <p></p>

      <div class="post-next-prev">
        <div class="padd">
          <!-- 上一篇 -->
          <div class="next-prev" v-if="neighborArticle[1]">
            <a :href="'/article-detail/'+neighborArticle[1].id" :title="neighborArticle[1].title">
              <div class="card">
                <div class="card-img">
                  <img :src="neighborArticle[1].image" :alt="neighborArticle[1].title">
                  <div class="overlay"></div>
                </div>
                <div class="card-body">
                  <h2 class="card-title">{{neighborArticle[1].title}}</h2>
                  <div class="card-footer">

                    <i class="fa fa-angle-left"></i><span>上一篇</span>
                  </div>
                </div>
              </div>
            </a>
          </div>

          <!-- 下一篇 -->
          <div class="next-prev" v-if="neighborArticle[0]">
            <a :href="'/article-detail/'+neighborArticle[0].id" :title="neighborArticle[0].title">
              <div class="card">
                <div class="card-img">
                  <img :src="neighborArticle[0].image" :alt="neighborArticle[0].title">
                  <div class="overlay"></div>
                </div>
                <div class="card-body">
                  <h2 class="card-title">{{neighborArticle[0].title}}</h2>
                  <div class="card-footer">
                    <span>下一篇</span>
                    <i class="fa fa-angle-right"></i>
                  </div>
                </div>
              </div>
            </a>
          </div>

        </div>
      </div>
    </article>


    <!-- 评论系统 -->

    <Twikoo/>


    <!-- 目录 -->
    <div v-show="Object.keys(outline).length > 0" ref="outline" id="directory-content"
         class="directory-content initial  unpinned" :class="{'mobile-dir':showMobileDir}"
         @click="showMobileDir = false">
      <div id="directory" class="clearfix">
        <ul>
          <li v-for="(item,i) of outline">
            <a @click="anchorPoint(item.id)" href="javascript:">{{ (i + 1) + ' ' + item.id }}</a>
            <ul v-if="item.children && item.children.length > 0">
              <li v-for="(tmp,j) of item.children">
                <a @click="anchorPoint(tmp.id)" href="javascript:">{{ (i + 1) + '.' + (j + 1) + ' ' + tmp.id }}</a>
                <ul v-if="tmp.children && tmp.children.length > 0">
                  <li v-for="(m,n) of tmp.children">
                    <a @click="anchorPoint(m.id)" href="javascript:">{{ (i + 1) + '.' + (j + 1) + '.' + (n + 1) + ' ' +
                      m.id }}</a>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>

    <!-- 图片的viewer -->
    <!-- <canvas id="evanyou-canvas"  style="position: fixed; top: 0; left: 0; z-index:-1; width: 100%; pointer-events: none;"></canvas> -->

    <!-- 支持的review -->

    <transition name="fade">
      <div class="wrap" v-if="showSupportModal">
        <img alt="" src="@/assets/img/appreciationCode.jpg">
      </div>
    </transition>
    <div class="support-wrap" v-show="showSupportModal">
    </div>

    <!-- 移动端目录 -->
    <a v-show="Object.keys(outline).length > 0" @click.stop="showMobileDir = true" class="mobile-directory"
       href="javascript:">
      <i class="fa fa-align-left"></i>
    </a>

  </layout-slot>
</template>
<script>
  import settings from '~/settings'
  import { canvasDraw, encrypt, evanyou, getCommentsCount, listToTree, parseTime } from '~/utils'
  import VditorPreview from 'vditor/dist/method.min'
  import { Fancybox } from '@fancyapps/ui'
  import '@fancyapps/ui/dist/fancybox.css'
  import Cookies from 'js-cookie'
  import { getReArticle, recordCount } from '~/api'

  export default {
    name: 'ArticleDetailPage',
    data () {
      return {
        articleDetail: {
          comments: {},
          footerStatement: {
            name: '-'
          },
          category: {
            url: '',
            title: ''
          },
          auth: ''
        },
        outline: [],
        password: '',
        neighborArticle: [],
        showSupportModal: false,
        showMobileDir: false,
        title: '',
        content: '',
        keywords: '',
        reArticle: []
      }
    },
    props: {
      id: [Number, String]
    },
    computed: {
      appreciationCode () {
        return this.$store.state.blogInfo.appreciationCode
      }
    },
    head () {
      return {
        title: this.title,
        meta: [
          {
            hid: 'description',
            name: 'description',
            content: this.content
          },
          {
            hid: 'keywords',
            name: 'keywords',
            content: this.keywords
          }
        ]
      }
    },
    methods: {
      anchorPoint (id) {
        let base = document.getElementsByClassName('main-content')[0].offsetTop
        let target = document.getElementById(id)
        if (target) {
          window.scrollTo({
            top: target.offsetTop + base,
            behavior: 'smooth'
          })
        }
        this.$router.push(`${this.$route.path}#${id}`)
      },
      articleByPass () {
        // this.getArticleDetail()
        this.$cookies.set('ARTICLE__pASS' + this.$route.params.id, encrypt(String(this.password)), {
          path: '/',
          maxAge: 60 * 60 * 24 * 30
        })
        window.history.go(0)
      },
      makeTreeData (h_serial, hr, id, hash) {

        let pid = id, key = `h${h_serial}`, keyLast = `h${Number(h_serial) + 1}`
        if (h_serial === 1) {
          pid = ''
        } else {
          if (!hash[key] && hr[hr.length - 1]) {
            hash[key] = hr[hr.length - 1]
          }
          if (hash[key] && hash[key].h_serial != h_serial) {
            pid = hash[key].id
          } else {
            pid = ''
          }
        }
        hash[keyLast] = ''

        hr.push({
          h_serial,
          id,
          pid: pid,
        })

      },
      getCatalog (textHtml) {
        let converter = document.createElement('DIV')
        converter.innerHTML = textHtml

        let elements = converter.getElementsByTagName('*')
        let html = `<ul level="1">`, serial = 0, flag = 0, num = {}, serial1 = 0, hr = [], hash = {}, tocHTML = ''
        for (let i = 0; i < elements.length; i++) {
          let item = elements[i]
          if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
            let id = item.getAttribute('id')
            let h_serial = item.tagName.substr(1, 1)
            if (h_serial == 1) {
              serial++
              serial1 = 0
              num[serial] = {
                inner: `${serial} ${item.innerText.replace(/\s/g, '')}`,
                children: [],
                id: item.innerText.replace(/\s/g, '')
              }
            } else if (h_serial == 2) {
              serial1++
              if (num[serial]) {
                num[serial].children.push({
                  inner: `${serial}.${serial1} ${item.innerText.replace(/\s/g, '')}`,
                  children: [],
                  id: item.innerText.replace(/\s/g, '')
                })
              }
            } else if (h_serial == 3) {

            }
            // 构造树形结构的数据
            this.makeTreeData(Number(h_serial), hr, id, hash)
          }
        }
        // console.log(hr)
        hr = listToTree(hr, 'id', 'pid')
        // console.log(hr)
        return hr
      },
      renderArticle () {
        let article = this.articleDetail

        // const MdIt = require("hexo-renderer-multi-markdown-it")
        // console.log(MdIt) https://juejin.cn/post/6844904105970761741 https://markdown-it.docschina.org/#%E8%AF%AD%E6%B3%95%E6%8B%93%E5%B1%95

        this.outline = this.getCatalog(article.body)

        // render start

        Fancybox.bind('.post-content img', {
          // Your options go here
          groupAll: true
        })

        if (this.$route.hash) {
          this.anchorPoint(decodeURIComponent(this.$route.hash.replace('#', '')))
        }

        let images = document.querySelectorAll('.post-content img')

        images.forEach((el) => {
          el.onerror = function (e) {
            e.target.src = require('~/assets/img/error/load_failed.png')
          }
        })

        let codes = document.getElementsByTagName('code')


        if (codes && codes.length > 0) {
          for (let el of codes) {
            if (el) {
              let previous = el.parentElement
              let codeType = document.createElement('div')
              codeType.classList.add('code-type')
              if (el.classList[0]) {
                codeType.innerText = el.classList[0].split('-')[1]
              }
              if (previous) {
                previous.appendChild(codeType)
              }
            }
          }
        }

        // VditorPreview.preview(this.$refs.article_main, article.body, {
        //   cdn: 'https://test1.jsdelivr.net/npm/vditor@3.8.7',
        //   hljs: {
        //     enable: true,
        //     style: 'monokai',
        //     lineNumber: false
        //   },
        //   after: () => {
        //     if (this.$route.hash) {
        //       this.anchorPoint(decodeURIComponent(this.$route.hash.replace('#', '')))
        //     }
        //     let images = document.querySelectorAll('.post-content img')
        //     images.forEach((el) => {
        //       el.onerror = function (e) {
        //         e.target.src = require('~/assets/img/error/load_failed.png')
        //       }
        //     })
        //     this.$store.commit('SET_STORE_VALUE', {
        //       subTitle: article.articleTitle
        //     })
        //     // 代码样式重制
        //     let codes = document.getElementsByTagName('code')
        //     if (codes && codes.length > 0) {
        //       for (let el of codes) {
        //         if (el) {
        //           let previous = el.parentElement
        //           let codeType = document.createElement('div')
        //           codeType.classList.add('code-type')
        //           if (el.classList[0]) {
        //             codeType.innerText = el.classList[0].split('-')[1]
        //           }
        //           if (previous) {
        //             previous.appendChild(codeType)
        //           }
        //         }
        //       }
        //     }
        //   }
        // })
        // render end

      },
      recordView () {
        recordCount(this.$axios, { id: this.$route.params.id }).then((res) => {
        })
      },
    },
    mounted () {
      new Headroom(this.$refs.outline, {
        offset: this.$refs.article_body.offsetTop,
        tolerance: 0,
        classes: {
          initial: 'headroom',
          pinned: 'slideDown',
          unpinned: 'slideUp'
        }
      }).init()

      // 评论多少
      getCommentsCount([`/article-detail/${this.$route.params.id}`]).then((res) => {

        if (Array.isArray(res)) {
          this.articleDetail.comments = {
            number: res[0].count,
            url: res[0].url
          }
        }
      })

      evanyou()

      canvasDraw()

      // 渲染
      this.$nextTick(() => {
        this.renderArticle()
      })

      this.recordView()

      document.body.addEventListener('click', () => {
        this.showSupportModal = false
      })
    },
    fetch () {
      //console.log(this.articleDetail)
    },
    async asyncData ({ params, app, }) {

      // console.log(app.$router,$route)
      let id = params.id, password = ''
      let pass = String(app.$cookies.get('ARTICLE__pASS' + id))

      // 获取文章信息
      let data = {
        id: params.id,
        password: encrypt(pass)
      }, neighborArticle = {}, articleDetail = {}, article = {}
      await app.$axios({
        method: 'POST',
        url: '/article/getById',
        data
      }).then(({ data }) => {
        if (data.code === 200) {
          neighborArticle = data.neighborArticle
          article = data.data
          // console.log(article)
          articleDetail = {
            isTop: true,
            color: settings.textColors[1],
            url: `/article-detail/${article.oId}`,//item.articlePermalink,
            src: article.articleImg1URL,
            title: article.articleTitle,
            Topping: true,
            time: article.articleCreated,
            // category: {
            //   title: article.categoryTitle,
            //   url: '/category/' + article.categoryURI
            // },
            category: {
              title: article.categoryTitle ? article.categoryTitle : '-',
              url: article.categoryURI ? article.categoryURI : '-'
            },
            comments: {
              number: article.articleCommentCount,
              url: '/'
            },
            views: ++article.articleViewCount,
            abstract: article.articleAbstract,
            tags: article.articleTags.split(',').map(item => ({
              name: item,
              url: '/tag/' + item
            })),
            body: article.articleContent,
            auth: article.auth,
            footerStatement: {
              updateTime: parseTime(article.articleUpdated),
              name: 'zipfang',
              url: '/about'
            }
          }
        }
      })
      let blogTitle = '', subTitle = articleDetail.title
      await app.$axios({
        url: '/blog/info/get',
        method: 'GET'
      }).then(({ data }) => {
        let blogInfo = {}
        for (let item of data.data.blogInfo) {
          blogInfo[item.oId] = item.optionValue
        }
        blogTitle = blogInfo.blogTitle
      })

      // 还是只能在这块的时候渲染

      let reArticle = await getReArticle(app)
      let result = {
        neighborArticle,

        title: `${subTitle} -${blogTitle}`,
        keywords: article.articleTags,
        content: article.articleAbstract,
        reArticle: reArticle
      }
      if (Object.keys(articleDetail).length > 0) {
        result.articleDetail = articleDetail
      }
      return result
    }
  }
</script>
<style lang="scss" scoped>
  .article-main {

  }



  // 针对整个文章的渲染
  .wrap {
    left: 50%;
    top: 50%;
    margin-top: -165px;
    margin-left: -165px;
    border-radius: 3px;
    position: fixed;
    width: 330px;
    height: 330px;
    overflow-y: auto;
    z-index: 1111;
    background: rgb(57, 61, 73);
    /*box-shadow: 1px 1px 20px 2px #888;*/
    transition: all .8s;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 250px;
    }

    /*&:hover {*/
    /*  transform: scale(1.4);*/
    /*}*/
  }

  .fade-enter-active, .fade-leave-active {
    transition: all .2s;

  }

  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */
  {
    opacity: 0;
    transform: scale(.6);

  }

  //.con {
  //  transform: translateX(-50%, -50%) scale(0.8, 0.8);
  //  left: 50%;
  //  top: 50%;
  //  border-radius: 3px;
  //  position: fixed;
  //  width: 220px;
  //  height: 220px;
  //  overflow-y: auto;
  //  z-index: 1111;
  //  transition: all .3s;
  //  visibility: hidden;
  //  background: #f2f2f2;
  //  opacity: 0;
  //}
  //
  //.show {
  //  transform: translateX(-50%, -50%) scale(1, 1);
  //  visibility: visible;
  //  opacity: 1;
  //
  //}
</style>
<style lang="scss">
  .article-content {
    max-width: 100%;
  }

  .support-wrap {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, .3);
    z-index: 1000;
  }
</style>
